
var FrameManager = require('FrameManager')

cc.Class({
    extends: cc.Component,

    properties: {
        control :require('Control'),
        roleMgr :require('RoleManager'),
        mapMgr : require('MapManager'),
        colliderMgr:require('ColliderManager'),
        camera : cc.Camera,
        spImage : cc.Sprite
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    preload(fcb){
        
        var farr = [];
        var weapon = global.DataCfg.player.weapon;
        var spriteFrames = {};

        function loadBullet(team){
            for(var i=0; i<team.length; i++){
                var name = team[i].name;
                var weapon = global.DataCfg.weapon[name]
                let sf = weapon.spriteFrame;
                if(!spriteFrames[sf]){
                    spriteFrames[sf] = 1
                    farr.push(function(tcb){
                        cc.loader.loadRes(sf,cc.SpriteFrame, function(err,res){
                            global.Textures[sf] = res;
                            tcb(err,res);
                        })
                    })
                }
            }
        }
        loadBullet(weapon.normal.left);
        loadBullet(weapon.normal.right);

        farr.push(function(tcb){
            cc.loader.loadResDir('Game/monster',cc.Prefab,function(err,arr){
                arr.forEach(function(p){
                    global.Loader.addPrefab('Game/monster/'+p._name,p);
                })
                tcb(err,arr)
                // for()
            })
        })

        var asy = new CCAsync();
        asy.parallel(farr,function(err,res){
            cc.log('加载结果 :',res);
            if(res){
                fcb && fcb()
            }
        })
    },

    start () {
        this.bulletLayer = cc.find('world/bulletLayer',this.node)
        this.bulletMgr = this.bulletLayer.getComponent('BulletManager')
        this.control.node.on('control',this.onControl,this);
        this.control.node.on('onbtn',this.onControlBtn,this);
        
        global.Socket.off('loginSuccess')
        
        this.startListener();
        
        this.control.setTouchEnabled(true)
        this.n_frameTime = 0;

        
        var ui = global.Loader.getInstantiate('Game/UI/GameUI');
        this.camera.node.addChild(ui)
        this.gameUI = ui.getComponent('GameUI')
    },

    onDestroy(){
        FrameManager.removeAll()
        global.Socket.off('loginSuccess')
        global.Socket.off('join')
        global.Socket.off('userExit')

        global.Socket.off('frame')
        global.Socket.off('diss')
        global.Socket.off('game')
        global.Socket.off('userExit')
    },

    startGame(){
        this.isRuning = true;
        this.mapMgr.updateMapCollider();
        this.send('ready');
    },

    getFrameTime(){
        return this.n_frameTime;  
    },

    startListener(){
        var self = this;
        global.Socket.on('loginSuccess',function(res){
            global.Socket.send('join',0)
        })

        global.Socket.on('join',function(res){
            cc.log('加入房间成功',res);
            self.send('ready');
        })

        global.Socket.on('userExit',function(data){
            cc.log('userExit',data);
            self.roleMgr.removeUser(data.v);
            // self.role
        })

        global.Socket.on('diss',function(data){
            cc.log('');
            global.GameLoop.enterLobby()
        })

        global.Socket.on('frame',function(data){
            self.n_frameTime = data.v.t;
            // self.bulletMgr.frameUpdate(data.v.v);
        })
        
        global.Socket.on('game',function(data){
            // cc.log('resp game:',data)
            data = data.v;
            var key = data.ge;
            if(key == 'pnet'){
                // PNetWorld.syncData(data.v);
                // cc.log('pnet:',data.v);
            } else if(key == 'ready'){
                self.roleMgr.resetScene(data.v);
                self.mapMgr.resetScene(data.v.data.data.map);
            } else if(key == 'move'){
                self.roleMgr.moveMessage(data.v);
            } else if(key == 'shootd'){
                self.roleMgr.setShootAngle(data.v);
            } else if(key == 'dbox'){
                self.mapMgr.destroyMonster(data.v);
            } else if(key == 'bullet'){
                self.bulletMgr.frameUpdate(data.v);
            }
            else if(data.ge == 'newUser'){
                cc.log('newUser:');
                self.roleMgr.newUser(data.v.user,data.v.data);
            } else if(data.ge == 'submit'){
                data.v.pos && self.roleMgr.moveEnd(data.v)
            }
        })
    },

    onControl(e){
        // cc.log('oncontrol:',e);
        // this.roleMgr.localPlayer.setDirection(e);
        var a = {id:global.Data.id,point:this.roleMgr.localPlayer.node.getPosition(),direction:e}
        this.send('move',a);
        this.submitUser(a)
        if(e.equals(cc.Vec2.ZERO)){
            this.roleMgr.localPlayer.setDirection(e);
        }
    },
    onControlBtn(d){
        if(this.roleMgr.localPlayer.shootAngle == d){
            return;
        }
        this.send('shootd',{id:global.Data.id,sa:d})
    },
    isHost(){
        return global.Data.id == 0;
    },

    getPlayers(){
        return this.roleMgr._players;
    },
    getPlayerLength(){
        return Object.keys(this.roleMgr._players).length
    },


    send(k,v={}){
        var gd = {
            ge : k,
            v:v
        }
        global.Socket.send('game',gd)
    },
    submitUser(d){
        this.send('suser',d)
    },
    submitData(d){
        cc.log('submitData:',d);
        this.send('sdata',d)
    },
    submitFrame(d){
        this.send('bullet',d)
    },
    update(dt){
        if(!this.isRuning){
            return
        }
        this.roleMgr.gameUpdate(dt);
        this.mapMgr.gameUpdate(dt);

        this.colliderMgr.gameUpdate(dt);
        FrameManager.gameUpdate(dt);

        if(this.roleMgr.localPlayer){
            this.camera.node.y = Math.max(this.roleMgr.localPlayer.node.y,this.camera.node.y)
        }

        // this.n_frameTime += Math.floor(dt*1000);
        // var y = (this.n_frameTime - 3000) / 1000 * 30
        // if(y > 0){
        //     this.camera.node.y = Math.max(y,this.camera.node.y)
        // }
    },
    lateUpdate(dt){
    }
    

    // update (dt) {},
});
